import { maccApi, requestHttp, terminalTools, topoTools } from '@utils/index';

import {
  getSwitchOrder, //获取交换机order
} from '@utils/deviceTools';

const topoDataMixin = {
  data() {
    return {
      topoData: {},
      topOptions: {
        terminalTypeMap: {},
        modal: 'devices', //三种模式,1. devices 普通展示 2.markup 拓扑补全模式 3,virtualview  显示未知拓扑补全按钮
        multipleSelect: false, //是否可以多选节点
        filterClass: [], //禁止点击设备类型
        isDeviceGroup: true, //是否打包终端设备 AP/IPC
        expansionNodeGroup: true, //是否允许展开设备组
      },
      topoDataLoading: false,
      trueDeviceList: [],
    };
  },
  methods: {
    /**
     * 获取拓扑数据
     * @param {boolean} [withWiredTerminal=false]
     * @returns
     */
    getTopoData(withWiredTerminal = false, groupId) {
      return new Promise((resolve, reject) => {
        const currGroupId = groupId || this.$store.state.Group.groupId;
        if (currGroupId) {
          let data = {
            api: maccApi.GET_TOPOLOGY_TREEDATA.replace(
              '{group_id}',
              currGroupId
            ).replace('{with_wired_terminal}', withWiredTerminal),
            method: 'GET',
          };
          requestHttp(data)
            .then((res) => {
              if (res && res.code == 0) {
                resolve(res.data);
              } else {
                reject(res);
              }
            })
            .catch((error) => {
              reject(error);
            });
        } else {
          resolve({});
        }
      });
    },
    /**
     * 获取拓扑中设备面板端口数据
     * @param {*} sns
     * @returns
     */
    getTopoDevicePanelPortsData(sns) {
      return new Promise((resolve, reject) => {
        let data = {
          api: maccApi.GET_DEVICE_PANELPOERTS,
          method: 'POST',
          params: { snList: sns },
        };
        requestHttp(data)
          .then((res) => {
            if (res && res.code == 0) {
              resolve(res.portMap);
            } else {
              reject(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /**
     * 格式化拓扑数据
     * @param {*} topoData 拓扑数据
     * @param {*} portsMap 设备面板端口数据MAP
     */
    formatterTopoData(topoData, portsMap) {
      if (topoData.deviceType != 'OUT' && topoData.isVirtualDev == false) {
        this.trueDeviceList.push(JSON.parse(JSON.stringify(topoData)));
      }

      if (topoData.deviceType && topoData.deviceType.endsWith('_GROUP')) {
        for (let i = 0; i < topoData._children.length; i++) {
          this.trueDeviceList.push(
            JSON.parse(JSON.stringify(topoData._children[i]))
          );
        }
      }

      if (this.topOptions.isDeviceGroup) {
        topoTools.rootPickDevice(topoData, 'AP');
        topoTools.rootPickDevice(topoData, 'ipc');
      }
      if (topoData.deviceSn) {
        //判断是否多面板交换机
        let multiPanel = false;
        if (topoData.productClass) {
          multiPanel =
            this.$store.state.devices.multiPanelClass.indexOf(
              topoData.productClass
            ) > -1;
        }

        topoData.portsData = this.formatterPortData(
          portsMap[topoData.deviceSn] || [],
          multiPanel
        );
        //添加设备端口原始数据用来不去拓扑时端口使用
        topoData.portsAliasMap = portsMap[topoData.deviceSn] || [];
      }
      let children = topoData.children || topoData._children || [];
      if (children.length > 0) {
        for (let i = 0; i < children.length; i++) {
          this.formatterTopoData(children[i], portsMap);
        }
      }
    },
    /**
     * 格式化设备端口面板数据
     * @param {*} portsData
     * @param {*} multiPanelFlag 是否多面板交换机
     * @returns
     */
    formatterPortData(portsData, multiPanelFlag) {
      let portData = {};
      for (let i = 0; i < portsData.length; i++) {
        let item = portsData[i];

        let port = {
          name: item.name,
          order: getSwitchOrder(item),
          mediumType: item.mediumType,
          portClass: [],
          exceptionColor: 'grey', //不可用端口颜色
          portGroupId: item.portGroupId,
        };

        if (item.enable == 'false') {
          port.portClass.push('grey');
        }

        if (item.status == 'Up') {
          if (['10M', '100M'].indexOf(item.speed) > -1) {
            port.portClass.push('yellow');
          } else {
            port.portClass.push('green');
          }
        }
        //多面板交换机portDataMap不同命名规则
        if (multiPanelFlag) {
          portData[item.name] = port;
        } else {
          portData[getSwitchOrder(item)] = port;
        }
      }

      return portData;
    },
    /**
     * 初始化拓扑
     * @param {*} withWiredTerminal
     */
    initTopo(withWiredTerminal = false, groupId) {
      const self = this;
      self.topoDataLoading = true;
      this.getTopoData(withWiredTerminal, groupId).then((topoData) => {
        self.initViewTopo(withWiredTerminal, topoData);
      });
    },
    /**
     * 真正开始渲染拓扑图
     * @param {*} withWiredTerminal
     * @param {*} topoData
     * @returns
     */
    initViewTopo(withWiredTerminal, topoData) {
      const self = this;
      if (topoData == undefined || JSON.stringify(topoData) == '{}') {
        self.topoDataLoading = false;
        self.topoData = topoData;
        return;
      }
      let networkPanelClass = [],
        sns = [];
      let deviceLayouts = self.$store.state.devices.deviceLayout;
      topoTools.getNetworkDeviceClass(
        topoData || {},
        deviceLayouts,
        networkPanelClass,
        sns
      );
      let promiseList = [];
      promiseList.push(self.getTopoDevicePanelPortsData(sns));

      if (withWiredTerminal) {
        promiseList.push(terminalTools.getTerminalTypeList());
      }
      //当网络中的设备面板在store中不存在时，请求面板布局数据并存入store
      if (networkPanelClass.length > 0) {
        promiseList.push(
          self.$store.dispatch('devices/updataDeviceLayout', networkPanelClass)
        );
      }

      Promise.all(promiseList)
        .then((result) => {
          console.log('网络中设备面板端口信息', result[0]);
          self.trueDeviceList = [];
          self.formatterTopoData(topoData, result[0]);
          if (withWiredTerminal) {
            let terminalTypeMap = terminalTools.getTerminalTypeIconMap(
              result[1]
            );
            console.log('终端类型列表', terminalTypeMap);
            self.topOptions.terminalTypeMap = terminalTypeMap;
          }
          console.log('拓扑数据', topoData);
          self.topoData = topoData;
          self.topoDataLoading = false;
        })
        .catch((error) => {
          console.log(`更新面板布局失败`, error, error[0]);
          self.topoDataLoading = false;
        });
    },
    /**
     *
     * 设置拓扑节点的样式
     * @param {*} deviceSnList
     */
    setNodeClass(deviceSnList, nodeClass, type) {
      topoTools.setNodeClass(deviceSnList, nodeClass, type);
    },
  },
};

export default topoDataMixin;
